package cn.lhn.ridersclub.aspect;

import cn.lhn.ridersclub.util.JwtUtil;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Aspect
@Component
public class TokenAspect {

    @Pointcut("@annotation(cn.lhn.ridersclub.anno.TokenVerify)")
    public void tokenAspect() {}

    @Before("tokenAspect()")
    public void verifyToken() throws RuntimeException {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attr != null) {
            HttpServletRequest request = attr.getRequest();

            String token = request.getHeader("authorization");
            String arg0 = request.getHeader("arg0");
            String arg1 = request.getHeader("arg1");

            //  验证Token
            Map<String, String> map = JwtUtil.verifyToken(token);
            String id = map.get("id");
            String email = map.get("email");

            //  验证id和email是否匹配
            if (!id.equals(arg0) || !email.equals(arg1)) {
                throw new RuntimeException("认证失败");
            }
        }
        else {
            throw new RuntimeException("认证失败");
        }
    }
}
